<?php

require_once '../config/class.mysql.php';
require_once '../config/metadata.php';
require_once '../config/funciones.php';
require_once '../config/controller.php';
require_once '../views/ViewAdminController.php';
require "../inc/simpleimage.php";

class VideosController extends Controller {

	protected static $baseUrl = '/panel/videos.php';

	public function index_action() {
		$metadata = array('title' => "Gestión fotos");
		$error = $this->getParam('error');

		$categorias = $this->Mysql->getAll('categorias', 'id, nombre');
		$videos = $this->Mysql->getJoin(array('videos','categorias'), 'categorias.nombre, videos.*', array('videos.id_categoria', 'categorias.id'),  'LEFT');
		$data = array(
			'title' => "Gestión fotos",
			'categorias' => $categorias,
			'videos' => $videos,
			'baseUrl' => self::$baseUrl,
			'error' => $error
		);

		$this->viewController->render('videos', $data, $metadata);
	}

	public function insertar_action() {

		if(isset($_POST['categoria']) && isset($_POST['enlace']) ){
			$errorCode = '';

			$name = $this->Mysql->getLast('videos','id');
			$rest = $name['id']++;
			$file_name = 'video'.str_pad($rest, 4, 0, STR_PAD_LEFT);
	
			$url = explode('/', $_POST['enlace']);
			$count = count($url);
			$identificador = $url[($count - 1)];

			if((strpos($identificador, '?') === false) && (strpos($identificador, '=') === false)) {
				$ch = curl_init('http://img.youtube.com/vi/' . $identificador . '/1.jpg');
				$fp = fopen("../videos/".$file_name .'.jpg', 'wb');
				curl_setopt($ch, CURLOPT_FILE, $fp);
				curl_setopt($ch, CURLOPT_HEADER, 0);
				curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
				curl_exec($ch);
				curl_close($ch);
				fclose($fp);
				if (!$this->Mysql->insert('videos', array($identificador, $file_name, $_POST['titulo'], $_POST['categoria'])))
					$errorCode = 2;
			}

			else  $errorCode = 1;
		}
		$this->redirect('index', $errorCode);
	}

	public function borrar_action() {
		if(isset($_GET['id']) && isset($_GET['thumb']) ){
			$this->Mysql->delete('videos', array('id' => $_GET['id']));
			unlink("../videos/".$_GET['thumb'].".jpg");
		}
		$this->redirect();
	}

	public function editar_action() {
		if(isset($_POST['titulo']) && isset($_POST['id-video']) && isset($_POST['video-cat'])){
			$this->Mysql->update('videos', array('titulo' => $_POST['titulo'], 'id_categoria' => $_POST['video-cat']), "id='".$_POST['id-video']."'");
		$this->redirect();
        }

		
	}

}

$controller = new VideosController('ViewAdminController', true);
$controller->dispatch();
